package top.codef.converters;

import java.util.Locale;

import javax.money.CurrencyUnit;
import javax.money.Monetary;

import org.javamoney.moneta.FastMoney;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

@Converter
public class FastMoneyPower2Converter implements AttributeConverter<FastMoney, Long> {

	@Override
	public Long convertToDatabaseColumn(FastMoney attribute) {
		if (attribute != null) {
			Long money = attribute.scaleByPowerOfTen(2).getNumber().longValue();
			return money;
		}
		return null;
	}

	@Override
	public FastMoney convertToEntityAttribute(Long dbData) {
		CurrencyUnit currencyUnit = null;
		try {
			currencyUnit = Monetary.getCurrency(Locale.getDefault());
		} catch (Exception e) {
			currencyUnit = Monetary.getCurrency(Locale.CHINA);
		}
		if (dbData != null) {
			FastMoney fastMoney = FastMoney.of(dbData, currencyUnit).scaleByPowerOfTen(-2);
			return fastMoney;
		}
		return null;
	}
}
